package com.fulihui.wgj.admin.api.base;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.fulihui.common.builder.web.JsonResultBuilder;
import com.fulihui.common.result.web.Result;
import com.fulihui.wgj.admin.config.properties.AdminProperties;
import com.fulihui.wgj.admin.config.properties.JwtProperties;
import com.fulihui.wgj.admin.security.jwt.JwtHelper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;

import javax.servlet.http.HttpServletRequest;

import static com.fulihui.common.constants.JwtConstants.ACCESS_JWT_TOKEN;
import static com.fulihui.common.constants.JwtConstants.APPID_KEY;
import static com.fulihui.common.error.Errors.Commons.REQUEST_PARAMETER_ERROR;

/**
 * @author: Levon
 * @version: v 0.1 2018-06-08 11:09
 */
public class BaseController {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private AdminProperties adminProperties;

    private ThreadLocal<Claims> claimsThreadLocal = new ThreadLocal<>();

    public Result valid(BindingResult validResult) {
        if (validResult.hasErrors()) {
            for (ObjectError error : validResult.getAllErrors()) {
                return JsonResultBuilder.fail(REQUEST_PARAMETER_ERROR.getErrcode(), error.getDefaultMessage());
            }
        }
        return null;
    }

    @ModelAttribute
    public void initJWT(@RequestHeader(name = ACCESS_JWT_TOKEN, required = false) String jwToken) {
        if (StringUtils.isNotEmpty(jwToken)) {
            try {
                Claims claims = JwtHelper.parseJWT(jwToken.substring(7), jwtProperties.getBase64Secret());
                claimsThreadLocal.set(claims);
            } catch (Exception ex) {

            }
        }
    }

    /**
     * 获取登录Id
     *
     * @return 当前登入用户的Id
     */
    protected String getLoginId() {
        if (claimsThreadLocal.get() != null && claimsThreadLocal.get().containsKey(JwtHelper.LOGIN_ID)) {
            return claimsThreadLocal.get().get(JwtHelper.LOGIN_ID).toString();
        }
        return null;
    }

    /**
     * 获取公众号Id
     *
     * @return
     */
    protected String getAppid(HttpServletRequest request) {
        return request.getHeader(APPID_KEY);
    }
}
